/*
 * @Descripttion: 
 * @version: 
 * @Author: 付正生
 * @Date: 2022-07-06 09:21:41
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2022-08-25 22:06:10
 */
import Vue from "vue";
import VueDraggableResizable from "vue-draggable-resizable";
Vue.component("vue-draggable-resizable", VueDraggableResizable);
function initDrag(columns, that, localKey, BY) {
  const draggingMap = {};
  columns.forEach((col) => {
    draggingMap[col.key] = col.width;
  });
  Vue.observable(columns);
  const draggingState = Vue.observable(draggingMap);
  return (h, props, children) => {
    let thDom = null;

    const { key, ...restProps } = props;
    // 标识是否处于拖动状态
    let isDrag = false;
    let col;
    if (key === "selection-column") {
      //表格加了复选框，不加这个判断col会是undefided
      col = {};
    } else {
      col = columns.find((col) => {
        const k = col.dataIndex || col.key;
        return k === key;
      });
    }
    if (!col || !col.width || col.fixed && col.fixed == 'right') {
      return <th {...restProps}>{children}</th>;
    }
    const onDrag = (x) => {
      isDrag = true
      draggingState[key] = 0;
      col.width = Math.max(x, 60);
    };

    const onDragstop = () => {
      isDrag = true
      draggingState[key] = thDom.getBoundingClientRect().width;
      setTimeout(() => {
        isDrag = false
      }, 300)
      let locals = []
      for (let i = 0; i < that.columns.length; i++) {
        const item = that.columns[i];
        locals.push({
          isLock: !!item.fixed,
          number: i + 1,
          title: item.title,
          value: item.dataIndex,
          width: item.width
        })
      }
      let local = ''
      if (BY) {
        local = localKey
      } else {
        local = that.BUSI_CONST.Entity[localKey]
      }
      console.log(local,'locallocallocal');
      localStorage.setItem(local, JSON.stringify(locals))
      // console.log(that.columns,'showSetColumn');
    };
    // 处于拖动状态300ms之内阻止点击事件触发
    if (restProps.on && restProps.on.click) {
      let clickFunc = restProps.on.click
      restProps.on.click = (event) => {
        if (isDrag) {
          return;
        }
        clickFunc(event)
      }
    }
    return (
      <th
        {...restProps}
        v-ant-ref={(r) => (thDom = r)}
        width={col.width}
        class="resize-table-th"
      >
        {children}
        <vue-draggable-resizable
          key={col.key}
          class="table-draggable-handle"
          w={10}
          x={draggingState[key] || col.width}
          z={1}
          axis="x"
          draggable={true}
          resizable={false}
          onDragging={onDrag}
          onDragstop={onDragstop}
        ></vue-draggable-resizable>
      </th>
    );
  };
}
export default {
  methods: {
    drag(columns, localKey, BY) {
      return {
        header: {
          cell: initDrag(columns, this, localKey, BY),
        },
      };
    },
  },
};